<?php
namespace app\admin\service;

use app\model\ConsultTimeModel;
use app\model\DepartmentModel;
use app\model\UserModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Service;

class UserExportService extends Service
{
    /**
     * 普通用户导出
     * @param array $id
     * @param int $unit_id
     * @return string
     */
   public function UserExport(array $id,int $unit_id): string
   {
       // 创建新的Spreadsheet对象
       $spreadsheet = new Spreadsheet();
       // 获取活动的工作表
       $sheet = $spreadsheet->getActiveSheet();
       // 设置工作表标题
       $sheet->setTitle('普通用户');
       // 设置单元格数据
       $sheet->setCellValue('A1', '名称');
       $sheet->setCellValue('B1', '联系方式');
       $sheet->setCellValue('C1', '性别');
       $sheet->setCellValue('D1', '年龄');
       $sheet->setCellValue('E1', '身份证号');
       $sheet->setCellValue('F1', '注册账号');
//       $sheet->setCellValue('G1', '所在系别/学部');
       $sheet->setCellValue('G1', '所在部门');
//       $sheet->setCellValue('I1', '班级编号');
       $sheet->setCellValue('H1', '部门内部编号');
//       $sheet->setCellValue('K1', '学籍状态');
       $sheet->setCellValue('I1', '账号状态');
       $sheet->setCellValue('J1', '部门管理员');
       $UserModel = new UserModel();
       $data = $UserModel->where('id','in',$id)->select()->toArray();
       if (count($data) > 0) {
           $department_ids = array_column($data, 'department_id');
           $UserService = new UserService($this->app);
           $DepartmentAffiliationAll = $UserService->getDepartmentAffiliationAll($unit_id);
           $DepartmentAdminAll = $UserService->getDepartmentAdminAll($department_ids);
           foreach ($data as $key => $item) {
               //学籍状态
               $student_name = match ($item['student_status']) {
                   0 => '不限',
                   1 => '在读',
                   2 => '已毕业',
                   3 => '已退学',
                   4 => '休学',
                   default => '--',
               };
               //账号状态
               $status_name = match ($item['status']) {
                   1 => '正常',
                   2 => '禁用',
                   3 => '密码申诉中',
                   default => '--',
               };
               // 设置单元格数据
               $key = $key + 2;
               $sheet->setCellValue('A'.$key, $item['name']??'--');
               $sheet->setCellValue('B'.$key, $item['phone']??'--');
               $sheet->getStyle('B'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
               $sheet->setCellValue('C'.$key, $item['sex'] == 1 ? '男' : '女');
               $sheet->setCellValue('D'.$key, $item['age']?:'--');
               $sheet->setCellValue('E'.$key, $item['id_card']?:'--');
               $sheet->getStyle('E'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
               $sheet->setCellValue('F'.$key, $item['username']?:'--');
//               $sheet->setCellValue('G'.$key, $DepartmentAffiliationAll[$item['department_id']]['ascription_name']??'--');
               $sheet->setCellValue('G'.$key, $DepartmentAffiliationAll[$item['department_id']]['all_name']??'--');
//               $sheet->setCellValue('I'.$key, $DepartmentAffiliationAll[$item['department_id']]['number']??'--');
               $sheet->setCellValue('H'.$key, $item['user_number']?:'--');
//               $sheet->setCellValue('K'.$key, $student_name);
               $sheet->setCellValue('I'.$key, $status_name);
               $sheet->setCellValue('J'.$key, $DepartmentAdminAll[$item['department_id']]['user_name']??'--');
           }
       }
       $writer = new Xlsx($spreadsheet);
       $ext = '.xlsx';
       $save_name = '/export/user'.date('Ym').'/'.date('d').'_'.time().uniqid();
       $file_path  = dirname('./public' . $save_name.$ext);
       folder_build($file_path);
       $writer->save('./public' . $save_name . $ext);
       return oss('./public' . $save_name . $ext, $ext);
   }

    /**
     * 咨询师导出
     * @param array $id 列表id
     * @return string
     */
    public function ConsultExport(array $id): string
    {
        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        // 设置工作表标题
        $sheet->setTitle('咨询师');
        // 设置单元格数据
        $sheet->setCellValue('A1', '名称');
        $sheet->setCellValue('B1', '性别');
        $sheet->setCellValue('C1', '年龄');
        $sheet->setCellValue('D1', '所在单位');
        $sheet->setCellValue('E1', '注册账号');
        $sheet->setCellValue('F1', '排班情况');
        $sheet->setCellValue('G1', '排班剩余天数');
        $sheet->setCellValue('H1', '服务对象类型');
        $sheet->setCellValue('I1', '具体负责部门');
        $sheet->setCellValue('J1', '登录状态');
        $UserModel = new UserModel();
        $data = $UserModel->where('id','in',$id)->with([
            'unitName'
        ])->select()->toArray();
        if (count($data) > 0) {
            $time = time();
            $ConsultTimeModel = new ConsultTimeModel();
            $DepartmentModel = new DepartmentModel();
            foreach ($data as $key => $item) {
                //服务对象
                $department_id = $ConsultTimeModel->where([
                    ['consult_id','=',$item['id']],
                    ['start_time','>',$time]
                ])->distinct(true)->column('department_id');
                if (in_array(0,$department_id)) {
                    $ServerType = '所有部门';
                    $ServerName = '--';
                }else{
                    $ServerType = '服务指定部门';
                    $ServerName = $DepartmentModel->where('id','in',$department_id)->column('name');
                    $ServerName = implode('、',$ServerName);
                }
                //排班情况
                $ConsultDate = $ConsultTimeModel->where([
                    ['consult_id','=',$item['id']],
                    ['start_time','>',$time]
                ])->distinct(true)->column('date');
                $day = count($ConsultDate);
                //账号状态
                $status_name = match ($item['status']) {
                    1 => '正常',
                    2 => '禁用',
                    3 => '密码申诉中',
                    default => '--',
                };
                $key = $key + 2;
                $sheet->setCellValue('A'.$key, $item['name']??'--');
                $sheet->setCellValue('B'.$key, $item['sex'] == 1 ? '男' : '女');
                $sheet->setCellValue('C'.$key, $item['age']?:'--');
                $sheet->setCellValue('D'.$key, $item['unit_name']??'--');
                $sheet->setCellValue('E'.$key, $item['username']??'--');
                $sheet->setCellValue('F'.$key, $day ? '已排班' : '未排班');
                $sheet->setCellValue('G'.$key, $day ? $day.'天' : '--');
                $sheet->setCellValue('H'.$key, $ServerType);
                $sheet->setCellValue('I'.$key, $ServerName);
                $sheet->setCellValue('J'.$key, $status_name);
            }
        }
        $writer = new Xlsx($spreadsheet);
        $ext = '.xlsx';
        $save_name = '/export/consult'.date('Ym').'/'.date('d').'_'.time().uniqid();
        $file_path  = dirname('./public' . $save_name.$ext);
        folder_build($file_path);
        $writer->save('./public' . $save_name . $ext);
        return oss('./public' . $save_name . $ext, $ext);
    }

    /**
     * 管理员导出
     * @param array $id 列表id
     * @param int $unit_id
     * @return string
     */
    public function AdminExport(array $id, int $unit_id): string
    {
        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        // 设置工作表标题
        $sheet->setTitle('管理员');
        // 设置单元格数据
        $sheet->setCellValue('A1', '名称');
        $sheet->setCellValue('B1', '性别');
        $sheet->setCellValue('C1', '年龄');
        $sheet->setCellValue('D1', '注册账号');
        $sheet->setCellValue('E1', '所在单位');
        $sheet->setCellValue('F1', '账号等级');
        $sheet->setCellValue('G1', '管理部门');
        $sheet->setCellValue('H1', '登录状态');
        $UserModel = new UserModel();
        $data = $UserModel->where('id','in',$id)->with([
            'unitName',
            'DepartmentAdmins' => function ($queue) {
                $queue->with(['Department']);
            }
        ])->select()->toArray();
        if (count($data) > 0) {
            $UserService = new UserService($this->app);
            $DepartmentAll = $UserService->getDepartmentAffiliationAll($unit_id);
            foreach ($data as $key => $item) {
                $item['admin_department'] = '';
                if (count($item['DepartmentAdmins'])){
                    $field = [];
                    foreach ($item['DepartmentAdmins'] as $k => $row) {
                        $field[$k]  = $row['department_id'];
                    }
                    array_multisort($field, SORT_ASC, $item['DepartmentAdmins']); // 假设按’field’字段升序排序
                    foreach ($item['DepartmentAdmins'] as $v) {
                        if (empty($item['admin_department'])) {
                            $item['admin_department'] = $DepartmentAll[$v['department_id']]['all_name'] ?? '';
                        } else {
                            $item['admin_department'] .= '、' . $DepartmentAll[$v['department_id']]['all_name'] ?? '';
                        }
                    }
                }
                //账号状态
                $status_name = match ($item['status']) {
                    1 => '正常',
                    2 => '禁用',
                    3 => '密码申诉中',
                    default => '--',
                };
                $key = $key + 2;
                $sheet->setCellValue('A'.$key, $item['name']??'--');
                $sheet->setCellValue('B'.$key, $item['sex'] == 1 ? '男' : '女');
                $sheet->setCellValue('C'.$key, $item['age']?:'--');
                $sheet->setCellValue('D'.$key, $item['username']??'--');
                $sheet->setCellValue('E'.$key, $item['unit_name']??'--');
                $sheet->setCellValue('F'.$key, '普通管理员');
                $sheet->setCellValue('G'.$key, $item['admin_department']);
                $sheet->setCellValue('H'.$key, $status_name);
            }
        }
        $writer = new Xlsx($spreadsheet);
        $ext = '.xlsx';
        $save_name = '/export/admin'.date('Ym').'/'.date('d').'_'.time().uniqid();
        $file_path  = dirname('./public' . $save_name.$ext);
        folder_build($file_path);
        $writer->save('./public' . $save_name . $ext);
        return oss('./public' . $save_name . $ext, $ext);
    }

}